#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

static const uint16_t default_port = 8888;
static std::string default_ip = "127.0.0.1";

class UdpServer
{
public:
    UdpServer(const std::string& ip = default_ip, const uint16_t& port = default_port)
        :_port(port), _ip(ip)
    {
    }

    void InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0) 
        {
            std::cout << "Socket failed" << std::endl;
            exit(1); 
        }
        
        struct sockaddr_in serv_addr;
        memset(&serv_addr, 0, sizeof(serv_addr));
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(_port);
        //serv_addr.sin_addr.s_addr = inet_addr(_ip.c_str()); 
        serv_addr.sin_addr.s_addr = INADDR_ANY;

        int flag = bind(_sockfd, (const sockaddr*)&serv_addr, sizeof(serv_addr));
        if(flag < 0)
        {
            std::cout << "bind failed" << std::endl;
            exit(1);
        }
    }

    void Start()
    {
        char buffer[1024];
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (sockaddr*)&peer, &len);
            if(n > 0)
            {
                buffer[n] = 0;
                std::cout << "[client]:" << buffer <<std::endl;

                std::string Rebuff;
                Rebuff += "[Echo Server]:";
                Rebuff += buffer;

                sendto(_sockfd, Rebuff.c_str(), Rebuff.size(), 0, (const sockaddr*)&peer, len);
            }
            else
            {
                std::cout << "recvfrom failed" << std::endl;
            }
        }
    }

    ~UdpServer()
    {
        if(_sockfd > -1)
        {
            close(_sockfd);
        }
    }
private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;
};